package com.gxpt.app.view;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnItemLongClickListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.google.gson.Gson;
import com.gxpt.app.AppUtils;
import com.gxpt.app.BaseActivity;
import com.gxpt.app.Constant;
import com.gxpt.app.MessageEvent;
import com.gxpt.app.R;
import com.gxpt.app.adapter.shopping_applylist_list_Adapter;
import com.gxpt.app.bean.applylist_bean;
import com.gxpt.app.bean.orderlist_bean;
import com.utils.ScreenUtils;
import com.utils.T;
import com.utils.logger.Logger;
import com.utils.okhttputils.HttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;

import okhttp3.Call;

/**
 * Created by dufeng on 2017/8/4.
 */

@ContentView(R.layout.activity_center_applylist_shopping_list)
public class Activity_center_applylist_shopping_list extends BaseActivity {


    public static final int REQUEST_CODE_ADD  = 10001;
    public static final int REQUEST_CODE_EDIT = 10002;

    public static final int RERESULT_CODE_SUCCESS = 20001;

    /**服务器端一共多少条数据*/
    private static final int TOTAL_COUNTER = 10000;//如果服务器没有返回总数据或者总页数，这里设置为最大值比如10000，什么时候没有数据了根据接口返回判断

    /**每一页展示多少条数据*/
    private static final int REQUEST_COUNT = 20;

    /**已经获取到多少条数据了*/
    private static int mCurrentCounter = 0;

    private shopping_applylist_list_Adapter mDataAdapter = null;

    private LRecyclerViewAdapter mLRecyclerViewAdapter = null;

    ///////////////////
    int page_num  = 1;
    int page_size = 20;


    @ViewInject(R.id.mLRecyclerView)
    LRecyclerView mLRecyclerView;

    private View topView;

    @ViewInject(R.id.toback)
    Button toback;

    @ViewInject(R.id.to_add)
    Button to_add;

    @ViewInject(R.id.txt_title)
    TextView txt_title;

    int pic_view_width = 0;
    int pic_view_hight = 0;

    String ID;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        x.view().inject(this);

        initView();
        initData();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MessageEvent messageEvent){
        if(messageEvent.getMessageType() ==Constant.ACTION_order_cancel_or_delete){

            mLRecyclerView.refresh();

        }else if(messageEvent.getMessageType() ==Constant.ACTION_pay_success){

            mLRecyclerView.refresh();
        }
    }

    @Override
    public void initView() {
        txt_title.setText(getString(R.string.txt_my_back));
        int Sviewwidth  = ScreenUtils.getScreenWidth(context);//
        pic_view_width  = Sviewwidth / 4;
        pic_view_hight  = pic_view_width/10*9;

        ///////////////////////////////////////////
        mDataAdapter = new shopping_applylist_list_Adapter(context);
        mLRecyclerViewAdapter = new LRecyclerViewAdapter(mDataAdapter);
        mLRecyclerView.setAdapter(mLRecyclerViewAdapter);

//        DividerDecoration divider = new DividerDecoration.Builder(this)
//                .setHeight(R.dimen.default_divider_height)
//                .setPadding(R.dimen.default_divider_padding)
//                .setColorResource(R.color.split)
//                .build();

        mLRecyclerView.setLayoutManager(new LinearLayoutManager(context));

        mLRecyclerView.setRefreshProgressStyle(ProgressStyle.LineSpinFadeLoader);
        mLRecyclerView.setArrowImageView(R.drawable.ic_pulltorefresh_arrow);
        mLRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);

        //add a HeaderView
//        mLRecyclerViewAdapter.addHeaderView(topView);

        mLRecyclerView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {

                do_Refresh();
            }
        });

        //是否禁用自动加载更多功能,false为禁用, 默认开启自动加载更多功能

        mLRecyclerView.setLoadMoreEnabled(true);

        mLRecyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                do_LoadMore();
            }
        });

        //设置头部加载颜色
        mLRecyclerView.setHeaderViewColor(R.color.red, R.color.red ,android.R.color.white);
        //设置底部加载颜色
        mLRecyclerView.setFooterViewColor(R.color.red, R.color.red ,android.R.color.white);
        //设置底部加载文字提示
        mLRecyclerView.setFooterViewHint("拼命加载中","已经全部为你呈现了","网络不给力啊，点击再试一次吧");

        mLRecyclerView.refresh();

        mLRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (mDataAdapter.getDataList().size() > position) {
                    applylist_bean.applylist item = mDataAdapter.getDataList().get(position);
                        Bundle b = new Bundle();
                        b.putString("service_id",item.service_id);
                        jumpActivity(Activity_apply_goods_detail.class,b,false);
                }

            }

        });

        mLRecyclerViewAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public void onItemLongClick(View view, int position) {
//                ItemModel item = mDataAdapter.getDataList().get(position);
//                T.show(getApplicationContext(), "onItemLongClick - " + item.title,1);
            }
        });

    }

    @Override
    public void initData() {

    }

    private void do_Refresh(){
        mDataAdapter.clear();
        mLRecyclerViewAdapter.notifyDataSetChanged();//fix bug:crapped or attached views may not be recycled. isScrap:false isAttached:true
        mCurrentCounter = 0;
        page_num = 1;
        toNet_applylist();//最新
    }

    private void do_LoadMore(){
        page_num += 1;
        toNet_applylist();//最新
    }
    private void notifyDataSetChanged() {
        mLRecyclerViewAdapter.notifyDataSetChanged();
    }

    private void addItems(ArrayList<applylist_bean.applylist> list) {



        mDataAdapter.addAll(list);
        mCurrentCounter += list.size();
    }



    @Event(value={R.id.toback})
    private void getEvent(View view){
        switch(view.getId()){
            case R.id.toback:
                closeActivity();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_ADD:
                if(RERESULT_CODE_SUCCESS == resultCode){
                    mLRecyclerView.refresh();
                }

                break;
            case REQUEST_CODE_EDIT:
                if(RERESULT_CODE_SUCCESS == resultCode){
                    mLRecyclerView.refresh();
                }

                break;
        }
    }

    //////NET DO
    private void toNet_applylist(){
        hud.show();
        JSONObject jsonBody=new JSONObject();
        try {
            jsonBody.put("device_number",         AppUtils.get_device_id(context));
            jsonBody.put("device_type",           Constant.device_type);
            jsonBody.put("token",                 AppUtils.get_token(context));
            jsonBody.put("pageName",             "shopservice");
            jsonBody.put("serviceName",          "applylist");

            jsonBody.put("member_id",             AppUtils.get_user_id(context));
            jsonBody.put("page_num",              page_num);
            jsonBody.put("page_size",             page_size);
        } catch (JSONException e) {
            e.printStackTrace();
        }
//        Logger.i("URL_storeaddress = "+jsonBody.toString()+" ["+Constant.URL_applylist+"]");
        HttpUtils.http_post_string(Constant.URL_applylist,jsonBody.toString(),do_applylist);
    }

    StringCallback do_applylist = new StringCallback(){


        @Override
        public void onError(Call call, Exception e, int i) {
            Logger.e(e.getMessage());
            mLRecyclerView.refreshComplete(REQUEST_COUNT);
        }

        @Override
        public void onResponse(String s, int i) {
            mLRecyclerView.refreshComplete(REQUEST_COUNT);
            if(hud.isShowing()){
                hud.dismiss();
            }
//            Logger.e("data = "+s);
            try{
                applylist_bean data = new Gson().fromJson(s, applylist_bean.class);
                if(data.state !=1 ){
                    T.show(context,data.msg,0);
                }else{
                    if(data.data != null){
                        if(data.data.size()>0){
                            addItems((ArrayList)data.data);
                            notifyDataSetChanged();
                        }else{
                            page_num -= 1;
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };



//    private void showNormalDialog(){
//        /* @setIcon 设置对话框图标
//         * @setTitle 设置对话框标题
//         * @setMessage 设置对话框消息提示
//         * setXXX方法返回Dialog对象，因此可以链式设置属性
//         */
//        final AlertDialog.Builder normalDialog =
//                new AlertDialog.Builder(context);
//        normalDialog.setTitle(getResources().getString(R.string.txt_tishi));
//        normalDialog.setMessage(getResources().getString(R.string.txt_issuredel));
//        normalDialog.setPositiveButton(getResources().getString(R.string.txt_sure),
//                new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        //...To-do
//                        toNet_deladdress();
//                    }
//                });
//        normalDialog.setNegativeButton(getResources().getString(R.string.txt_cancel),
//                new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        //...To-do
//
//                    }
//                });
//        // 显示
//        normalDialog.show();
//    }
}
